<template>
  <el-dialog
    v-model="visible"
    title="图片上传识别"
    width="800px"
    :before-close="handleClose"
    destroy-on-close
  >
    <div class="upload-modal">
      <!-- 用户信息展示 -->
      <div class="user-info-section">
        <h4>👤 当前用户信息</h4>
        <div v-if="isUserLoggedIn" class="user-info-card">
          <div class="user-avatar">
            <el-avatar 
              :size="50" 
              :src="currentUser.avatar" 
              :icon="User"
            />
          </div>
          <div class="user-details">
            <div class="user-name">
              <el-icon><User /></el-icon>
              <span>{{ currentUser.nickname || '未设置昵称' }}</span>
            </div>
            <div class="user-id">
              <span class="label">用户ID:</span>
              <el-tag type="primary" size="small">{{ currentUser.id }}</el-tag>
            </div>
          </div>
        </div>
        <div v-else class="user-info-empty">
          <el-alert
            title="用户未登录"
            description="请先登录系统后再进行人脸识别操作"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>
      </div>

      <!-- 配置选择 -->
      <div class="config-section">
        <h4>⚙️ 人脸配置</h4>
        <el-form :model="recognizeForm" label-width="100px">
          <el-form-item label="配置选择" required>
            <el-select
              v-model="recognizeForm.configId"
              placeholder="请选择人脸识别配置"
              style="width: 100%"
              :loading="configLoading"
            >
              <el-option
                v-for="config in configList"
                :key="config.id"
                :label="config.name"
                :value="config.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户组ID">
            <el-input
              v-model="recognizeForm.groupId"
              placeholder="可选，用于分组管理"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 图片上传 -->
      <div class="upload-section">
        <h4>📁 图片上传</h4>
        <div class="upload-area">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            drag
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            :on-change="handleFileChange"
          >
            <div v-if="!uploadForm.file" class="upload-placeholder">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽图片到此处或 <em>点击上传</em>
              </div>
              <div class="el-upload__tip">
                支持 jpg/png 格式，文件大小不超过 10MB
              </div>
            </div>
            <div v-else class="upload-preview">
              <img :src="uploadForm.imageUrl" alt="预览图片" class="preview-image" />
              <div class="preview-overlay">
                <el-button type="danger" size="small" @click.stop="clearUpload">
                  <el-icon><Delete /></el-icon>
                  重新上传
                </el-button>
              </div>
            </div>
          </el-upload>
        </div>
      </div>

      <!-- 识别操作 -->
      <div class="action-section">
        <h4>🎯 识别操作</h4>
        <div class="action-buttons">
          <el-button
            type="primary"
            @click="() => handleRecognize('register')"
            :disabled="!canRecognize"
            :loading="recognizeLoading"
          >
            <el-icon><UserFilled /></el-icon>
            人脸注册
          </el-button>
          <el-button
            type="success"
            @click="() => handleRecognize('search')"
            :disabled="!canRecognize"
            :loading="recognizeLoading"
          >
            <el-icon><Search /></el-icon>
            人脸搜索
          </el-button>
          <el-button
            type="warning"
            @click="() => handleRecognize('detect')"
            :disabled="!canRecognize"
            :loading="recognizeLoading"
          >
            <el-icon><View /></el-icon>
            人脸检测
          </el-button>
        </div>
      </div>

      <!-- 识别结果 -->
      <div class="result-section" v-if="recognizeResult">
        <h4>📊 识别结果</h4>
        <div class="result-content">
          <div v-if="recognizeResult.success" class="result-success">
            <el-alert
              title="识别成功"
              type="success"
              :closable="false"
              show-icon
            >
              <template #default>
                <div class="result-details">
                  <div v-if="recognizeResult.data.userId" class="result-item">
                    <span class="result-label">用户ID:</span>
                    <el-tag type="primary">{{ recognizeResult.data.userId }}</el-tag>
                  </div>
                  <div v-if="recognizeResult.data.similarity" class="result-item">
                    <span class="result-label">相似度:</span>
                    <el-tag :type="getSimilarityType(recognizeResult.data.similarity)">
                      {{ (recognizeResult.data.similarity * 100).toFixed(2) }}%
                    </el-tag>
                  </div>
                  <div v-if="recognizeResult.data.faceCount" class="result-item">
                    <span class="result-label">人脸数量:</span>
                    <el-tag type="info">{{ recognizeResult.data.faceCount }}</el-tag>
                  </div>
                  <div v-if="recognizeResult.data.processTime" class="result-item">
                    <span class="result-label">处理时间:</span>
                    <el-tag type="info">{{ recognizeResult.data.processTime }}ms</el-tag>
                  </div>
                </div>
              </template>
            </el-alert>
          </div>
          <div v-else class="result-error">
            <el-alert
              title="识别失败"
              :description="recognizeResult.message"
              type="error"
              :closable="false"
              show-icon
            />
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="clearResult" v-if="recognizeResult">
          清除结果
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { User, UploadFilled, Delete, UserFilled, Search, View } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
import * as FaceApi from '@/api/infra/face'

interface Props {
  modelValue: boolean
  configList: any[]
  configLoading: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', result: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const userStore = useUserStore()
const uploadRef = ref()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 用户信息
const currentUser = computed(() => userStore.getUser)
const isUserLoggedIn = computed(() => !!currentUser.value?.id)

// 表单数据
const recognizeForm = ref({
  configId: null,
  userId: computed(() => currentUser.value?.id),
  groupId: ''
})

const uploadForm = ref({
  file: null as File | null,
  imageUrl: ''
})

// 识别状态
const recognizeLoading = ref(false)
const recognizeResult = ref(null)

// 计算属性
const canRecognize = computed(() => {
  return isUserLoggedIn.value && 
         recognizeForm.value.configId && 
         uploadForm.value.file
})

// 文件上传处理
const handleFileChange = (file: any) => {
  const rawFile = file.raw
  if (!rawFile) return
  
  // 检查文件类型
  if (!rawFile.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  // 检查文件大小 (10MB)
  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 10MB')
    return
  }
  
  uploadForm.value.file = rawFile
  uploadForm.value.imageUrl = URL.createObjectURL(rawFile)
  
  // 清除之前的识别结果
  recognizeResult.value = null
}

// 清除上传
const clearUpload = () => {
  uploadForm.value.file = null
  uploadForm.value.imageUrl = ''
  recognizeResult.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 识别操作
const handleRecognize = async (type: 'register' | 'search' | 'detect') => {
  if (!canRecognize.value) {
    ElMessage.warning('请先登录并选择配置，然后上传图片')
    return
  }
  
  recognizeLoading.value = true
  recognizeResult.value = null
  
  try {
    const formData = new FormData()
    formData.append('file', uploadForm.value.file!)
    formData.append('configId', recognizeForm.value.configId!.toString())
    formData.append('userId', recognizeForm.value.userId!.toString())
    if (recognizeForm.value.groupId) {
      formData.append('groupId', recognizeForm.value.groupId)
    }
    
    let result
    switch (type) {
      case 'register':
        result = await FaceApi.registerFace(formData)
        break
      case 'search':
        result = await FaceApi.searchFace(formData)
        break
      case 'detect':
        result = await FaceApi.detectFace(formData)
        break
    }
    
    recognizeResult.value = {
      success: true,
      data: result,
      type
    }
    
    ElMessage.success(`人脸${type === 'register' ? '注册' : type === 'search' ? '搜索' : '检测'}成功`)
    emit('success', result)
    
  } catch (error: any) {
    recognizeResult.value = {
      success: false,
      message: error.message || '识别失败',
      type
    }
    ElMessage.error(error.message || '识别失败')
  } finally {
    recognizeLoading.value = false
  }
}

// 获取相似度标签类型
const getSimilarityType = (similarity: number) => {
  if (similarity >= 0.9) return 'success'
  if (similarity >= 0.7) return 'warning'
  return 'danger'
}

// 清除结果
const clearResult = () => {
  recognizeResult.value = null
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  // 清理数据
  clearUpload()
  recognizeForm.value.configId = null
  recognizeForm.value.groupId = ''
  recognizeResult.value = null
}

// 监听弹窗打开，重置表单
watch(visible, (newVal) => {
  if (newVal) {
    recognizeForm.value.configId = null
    recognizeForm.value.groupId = ''
    clearUpload()
  }
})
</script>

<style scoped>
.upload-modal {
  padding: 20px 0;
}

.user-info-section,
.config-section,
.upload-section,
.action-section,
.result-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.user-info-section h4,
.config-section h4,
.upload-section h4,
.action-section h4,
.result-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.user-info-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.user-details {
  flex: 1;
}

.user-name {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
  font-weight: 500;
}

.user-id {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.upload-area {
  width: 100%;
}

.upload-demo {
  width: 100%;
}

.upload-placeholder {
  padding: 40px 20px;
  text-align: center;
}

.upload-preview {
  position: relative;
  display: inline-block;
}

.preview-image {
  max-width: 300px;
  max-height: 200px;
  border-radius: 6px;
}

.preview-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.result-details {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.result-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.result-label {
  font-weight: 500;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>